package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _16除自身以外数组的乘积
 * @description
 * @date 2023/06/07 20:46
 * <p>
 * ******************************************************
 */
public class _16除自身以外数组的乘积 {


    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] answer = new int[n];
        answer[0] = 1;
        int pre = 1;

        // 将前缀积放入答案中
        for (int i = 1; i < n; i++) {
            pre *= nums[i - 1];
            answer[i] = pre;
        }

        int next = 1;

        // 将后缀积与前缀积相乘放入答案中
        for (int i = n - 2; i >= 0; i--) {
            next *= nums[i + 1];
            answer[i] *= next;
        }

        return answer;
    }
}
